import os
import arcpy
import time

group = ["Bahia", "EspiritoSanto", "MinasGerias_BOTTOM", "MinasGerias_TOP", "Parana", "SaoPaulo", "RioDeJaneiro"]
year = ["2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018"]


# Function to tabulate MapBiomas land cover rasters to grid cells 
def tabulate_LC(Year, Group, retry_limit=2):
    attempts = 0
    success = False
    
    # Paths
    MapBiomas = "...Data/MapBiomas/Land Cover"
    Grids = "S:/AEC/PactoRestoration/Grids"
    Output = ".../Outputs/Land Cover"
    
    # Files
    LC_file = os.path.join(LC, f"LandCover_{Year}.tif")
    Units = os.path.join(Grids, f"Atlanticforest2ha_{Group}_5kmbuffer_2haGrid.shp")
    Tabulate_Output = os.path.join(Output, f"LandCover_{Group}_{Year}.dbf")
    
    while attempts < retry_limit and not success:
        try:
            print(f"Tabulating {Year} Land Cover for {Group} Spatial Units")
            print(f"Output will be saved to: {Tabulate_Output}")
            
            with arcpy.EnvManager(outputCoordinateSystem='PROJCS["South_America_Albers_Equal_Area_Conic",GEOGCS["GCS_South_American_1969",DATUM["D_South_American_1969",SPHEROID["GRS_1967_Truncated",6378160.0,298.25]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Albers"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-60.0],PARAMETER["Standard_Parallel_1",-5.0],PARAMETER["Standard_Parallel_2",-42.0],PARAMETER["Latitude_Of_Origin",-32.0],UNIT["Meter",1.0]]'): 
                arcpy.sa.TabulateArea(
                    Units, 
                    "PageName", 
                    LC_file, 
                    "Value", 
                    Tabulate_Output, 
                    LC_file, 
                    "CLASSES_AS_FIELDS"
                )
                
            success = True  # If no error occurs, mark as success
        except arcpy.ExecuteError:
            attempts += 1
            print(f"ArcPy error on attempt {attempts} for {Year} {Group}. Retrying...")
            time.sleep(1)  # Add a delay before retrying
        except Exception as e:
            attempts += 1
            print(f"General error on attempt {attempts} for {Year} {Group}: {e}")
            time.sleep(1)  # Add a delay before retrying

    if not success:
        print(f"Failed to process {Year} Land Cover for {Group} Spatial Units after {retry_limit} attempts.")
    
# Call function in a loop for all states and years
for Year in year:
    for Group in group:
        tabulate_LC(Year, Group)
